library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity quadrature_demo is
	port (
		clock: in std_logic;
        reset: in std_logic;
		channelA: in std_logic;
		channelB: in std_logic;
		count: out std_logic_vector(10 downto 0)
	);
end quadrature_demo;

architecture arch_quadrature of quadrature_demo is
    signal previous : std_logic_vector(1 downto 0);
	signal current : std_logic_vector(1 downto 0);
	signal counter : signed(10 downto 0); --moet nog range bij
begin

	seq: process(clock, reset)
		variable channelAB : std_logic_vector(3 downto 0);
		variable diff : signed(1 downto 0);
		variable after_reset : natural range 0 to 2;
	begin
        if (reset='1') then
            previous <= "00";
			after_reset := 0;
			current <= "00";
			counter <= (others => '0');
		elsif (rising_edge(clock)) then
			previous <= current;
			current <= channelA & channelB;
			
			if (after_reset = 2) then
				channelAB := previous & current;
				case channelAB is
					when "1110" => diff := "11";
					when "1101" => diff := "01";
					when "1011" => diff := "01";
					when "1000" => diff := "11";
					when "0100" => diff := "01";
					when "0111" => diff := "11";
					when "0010" => diff := "01";
					when "0001" => diff := "11"; 
					when others => diff := "00";
				end case;
				counter <= counter + diff;
			else
				after_reset := after_reset + 1;
			end if;
		end if;
	end process;
	
	count <= std_logic_vector(counter);
	
end arch_quadrature;
